package com.wsdcd.zlg.sb.model.service.impl;

import com.wsdcd.zlg.sb.core.exception.ERPException;
import com.wsdcd.zlg.sb.mapper.UserMapper;
import com.wsdcd.zlg.sb.model.entity.User;
import com.wsdcd.zlg.sb.model.service.UserService;
import com.wsdcd.zlg.sb.util.PageParameter;
import com.wsdcd.zlg.sb.util.PagerUtil;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

@AllArgsConstructor
@Service
public class UserServiceImpl implements UserService {
	private final UserMapper userMapper;

	@Override
	public User login(User user) throws ERPException {
		User oldUser = userMapper.getUserByUsername(user.getUsername());
		if(oldUser == null){
			throw new ERPException("用户名不存在");
		}else if(!oldUser.getPassword().equals(user.getPassword())){
			throw new ERPException("密码不正确");
		}
		return oldUser;
	}

	@Override
	public PagerUtil<User>  selectByPage(PageParameter pageParameter) {
		int count = userMapper.getCount();
		List<User> data = userMapper.selectByPage(pageParameter);
		return new PagerUtil<>(count, data);
	}

	@Override
	public void insert(User user) throws ERPException {
		User oldUser = userMapper.getUserByUsername(user.getUsername());
		if(oldUser != null){
			throw new ERPException("用户名已存在");
		}else {
			userMapper.insert(user);
		}
	}

	@Override
	public void update(User user) throws ERPException {
		User oldUser = userMapper.getUserByUsername(user.getUsername());
		if(oldUser == null){
			throw new ERPException("不能在修改中添加数据");
		}else if(oldUser.equals(user)){
			throw new ERPException("修改后不能和原先的数据相同");
		}else {
			userMapper.update(user);
		}
	}

	@Override
	public void delete(int id) {
		userMapper.delete(id);
	}

}
